package net.zoneland.knowledge.service.impl;

import java.util.List;
import java.util.Optional;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

import net.zoneland.knowledge.service.UomUserOrgService;
import net.zoneland.knowledge.uom.dao.UomUserOrgMapper;
import net.zoneland.knowledge.uom.model.UomDepartment;
import net.zoneland.knowledge.uom.model.UomDepartmentExample;
import net.zoneland.knowledge.uom.model.UomUser;
import net.zoneland.knowledge.uom.model.UomUserExample;
import net.zoneland.knowledge.utils.OrgInfoUtils;

/**
 * 人员组织业务接口实现.
 * @author zmq
 * @Date 2022/7/29 13:51
 */
@Service
public class UomUserOrgServiceImpl implements UomUserOrgService {

    /**
     * 人员组织数据接口.
     */
    @Autowired
    private UomUserOrgMapper uomUserOrgMapper;
    /**
     * 通过用户名模糊查询人员列表.
     *
     * @param companyDn 公司dn
     * @param userName  用户名
     * @param size 数量
     * @return 用户列表
     */
    @Override
    public List<UomUser> queryUser(final String companyDn, final String userName, final int size) {
        UomUserExample example = new UomUserExample();
        UomUserExample.Criteria criteria = example.createCriteria()
            .andDomainEqualTo("ZMCC")
            .andReadCodeLike("%,userList,%")
            .andUserNameLike("%" + userName + "%");
        if (StringUtils.isNotBlank(companyDn)) {
            criteria.andCompanyDnEqualTo(companyDn);
        }
        PageHelper.startPage(1, size > 0 ? size : 10);
        List<UomUser> res = uomUserOrgMapper.queryUsersByName(example);
        Optional.ofNullable(res)
            .ifPresent(it -> it.forEach(x -> x.setDeptFullName(OrgInfoUtils.convertDnToFullName(x.getDeptDn()))));
        return res;
    }

    /**
     * 通过用户名模糊查询部门列表.
     *
     * @param companyDn 公司dn
     * @param orgName   部门名称
     * @param size      数量
     * @return 用户列表
     */
    @Override
    public List<UomDepartment> queryDepartment(final String companyDn, final String orgName, final int size) {
        UomDepartmentExample example = new UomDepartmentExample();
        UomDepartmentExample.Criteria criteria = example.createCriteria()
            .andDomainEqualTo("ZMCC")
            .andReadCodeLike("%,userList,%")
            .andNameLike("%" + orgName + "%");
        if (StringUtils.isNotBlank(companyDn)) {
            criteria.andCompanyDnEqualTo(companyDn);
        }
        PageHelper.startPage(1, size > 0 ? size : 10);
        List<UomDepartment> res = uomUserOrgMapper.queryDeptsByName(example);
        Optional.ofNullable(res)
            .ifPresent(it -> it.forEach(x -> x.setFullName(OrgInfoUtils.convertDnToFullName(x.getDn()))));
        return res;
    }
}
